package com.zhongan.gateway.filter;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import lombok.extern.slf4j.Slf4j;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.zhongan.gateway.bean.Api;
import com.zhongan.gateway.bean.ApiAttribute;
import com.zhongan.gateway.common.constant.GwDeveloperApiConstant;
import com.zhongan.gateway.common.enums.GwAttributeEnum;
import com.zhongan.gateway.dto.RequestBase;
import com.zhongan.gateway.service.ApiService;

/**
 * 对参数的初始化操作
 */
@Component
public class AttributeInitZuulFilter extends ZuulFilter {
    private Logger log = LoggerFactory.getLogger(AttributeInitZuulFilter.class);
    @Resource
    private ApiService apiService;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 19;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {

        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        RequestBase re = (RequestBase) request.getAttribute("requestBase");
        Api api = (Api) request.getAttribute("api");
        //        Long apiId = (Long) request.getAttribute("apiId");

        List<ApiAttribute> methodAttributeList = apiService.selectApiAttrs(api.getId());
        if (null != methodAttributeList && !methodAttributeList.isEmpty()) {
            JSONObject obj = (JSONObject) re.getBizContent();
            for (ApiAttribute ma : methodAttributeList) {
                //04 为可配置参数
                if (GwDeveloperApiConstant.ATTRIBUTE_TYPE.equals(ma.getAttributeKind())) {
                    log.info("开始注入参数" + ma.getName());
                    String pvalue = null;
                    //网关智能注入参数
                    if (GwAttributeEnum.APPKEY.getCode().equals(ma.getName())) {
                        pvalue = re.getAppKey();
                    } else if (GwAttributeEnum.SERVICE_NAME.getCode().equals(ma.getName())) {
                        pvalue = re.getServiceName();
                    } else if (GwAttributeEnum.TECH_GW.getCode().equals(ma.getName())) {
                        pvalue = GwAttributeEnum.TECH_GW.getDefaultValue();
                    } else if (GwAttributeEnum.UUID.getCode().equals(ma.getName())) {
                        pvalue = (String) request.getAttribute("uuid");
                    } else {
                        pvalue = ma.getDefaultValue();
                    }
                    obj.put(ma.getName(), pvalue);

                }
            }
        }

        return null;
    }

}
